﻿using Microsoft.AspNetCore.SignalR;
using StackExchange.Profiling.Internal;
using System.Collections.Concurrent;
using XinLife.Common.SignalR;
using XinLife.Core.Helper;

namespace XinLife.Common.Filters
{
    /// <summary>
    /// 推送首页系统运行信息
    /// </summary>
    public class SystemService : IHostedService, IDisposable
    {
        private Timer _timer;
        private readonly ILogger<SystemService> _logger;
        private readonly IHubContext<ChatHub, IChatClient> _hubContext;
        private CancellationTokenSource _cts;

        public SystemService(ILogger<SystemService> logger, IHubContext<ChatHub, IChatClient> hubContext)
        {
            _logger = logger;
            _hubContext = hubContext;
            _cts = new CancellationTokenSource();
        }

        public void DoWork(object obj)
        {
            var connectionId = ChatHub.Connections.Select(t => t.Key).ToList();
            _hubContext.Clients.Clients(connectionId).ShowSystemInfo(new { system_info= HardwareMonitor.GetCPUUsage() }.ToJson());

            var cts = obj as CancellationTokenSource;
            if (!cts.Token.IsCancellationRequested)
                _timer.Change((Int32)TimeSpan.FromMinutes(3).TotalMilliseconds, Timeout.Infinite);
        }

        public virtual void Dispose()
        {
            _cts.Cancel();
            _timer?.Dispose();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("定时服务开启");
            _timer = new Timer(DoWork, _cts, (Int32)TimeSpan.FromSeconds(20).TotalMilliseconds, Timeout.Infinite);
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("定时服务关闭");
            _cts.Cancel();
            _timer.Change(Timeout.Infinite, 0);
            //_timer?.Dispose();
            return Task.CompletedTask;
        }
    }
}
